<template>
  <view class="root">
    <view class="content" v-show="!visibleCamera">
      <uni-forms ref="form" :model="form" validateTrigger="blur" :border="true" err-show-type="toast" label-width="95">
        <view class="title-require-style">房屋信息(必填)</view>
        <view class="content-inner-wrapper content-inner-wrapper-house">
          <uni-forms-item label="标准地址" name="addressDetail" required v-if="['edit'].includes(options.type)">
            <view class="form-content-item" @click="">
              <view class="uni-easyinput__content-input-view-item-form-yy">
                {{form.addressDetail}}
              </view>
            </view>
          </uni-forms-item>
          <uni-forms-item label="房屋类型" name="fFwlx" required key="fFwlx">
            <view class="form-content-item" @click="hadleShowPicker('house_type', 'fFwlx')">
              <uni-easyinput type="text" v-model="form.fFwlx_text" disabled disableColor="#ffffff" :inputBorder="false"
                placeholder="请选择" :clearable="true" />
              <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
            </view>
          </uni-forms-item>
          <uni-forms-item label="房屋状态" name="fFwzt" required key="fFwzt" v-if="form.fFwlx == 2">
            <view class="form-content-item" @click="hadleShowPicker('house_status', 'fFwzt')">
              <uni-easyinput type="text" v-model="form.fFwzt_text" disabled disableColor="#ffffff" :inputBorder="false"
                placeholder="请选择" :clearable="true" />
              <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
            </view>
          </uni-forms-item>
          <uni-forms-item label="房屋用途" name="fFwyt" required key="fFwyt">
            <view class="form-content-item" @click="hadleShowPicker('house_use', 'fFwyt')">
              <uni-easyinput type="text" v-model="form.fFwyt_text" disabled disableColor="#ffffff" :inputBorder="false"
                placeholder="请选择" :clearable="true" />
              <uni-icons type="right" size="21" color="#C2C0C0"></uni-icons>
            </view>
          </uni-forms-item>
        </view>
      </uni-forms>

      <view class="button-wrapper">
        <view class="cancel btn-item" @click="handleCancel">取消</view>
        <u-button class="custom-style" text="保存" @click="handleSubmit" :disabled="loading"
          :custom-style="customSubmitStyleHalf"></u-button>
      </view>

      <u-picker closeOnClickOverlay v-if="pickerShow" :show="pickerShow" :columns="pickerData" keyName="text"
        @confirm="onPickerConfirm" @cancel="pickerShow = false" @close="pickerShow = false"
        :defaultIndex="defaultIndex"></u-picker>
    </view>
    <yy-watermark></yy-watermark>
  </view>
</template>


<script>
  import {
    postAction
  } from '@/utils/request'
  import {
    findCompany,
    infoDetailSave
  } from '@/api/home'
  import moment from '@/utils/moment'
  import pickerMixin from '@/utils/picker-mixin'
  import {
    Toast,
    checkIDCard,
    getHeader,
    isLoading,
    navBack,
    parseJson,
    selectNation,
    uploadFile,
    customSubmitStyleHalf
  } from '@/utils/util'

  import _ from '@/utils/lodash.js'


  export default {
    mixins: [pickerMixin],
    data() {
      return {
        form: this.initForm(),
        clientId: this.$clientId,
        clientSecret: this.$clientSecret,
        baseImgUrl: this.$baseImgUrl,
        visibleCamera: false,
        rules: {
          addressDetail: {
            rules: [{
              required: true,
              errorMessage: '请选择标准地址！',
            }]
          },
          fFwlx: {
            rules: [{
              required: true,
              errorMessage: '请选择房屋类型！',
            }]
          },
          fFwyt: {
            rules: [{
              required: true,
              errorMessage: '请选择房屋用途！',
            }]
          },
        },
        dictMapping: {
          is_house_owner: [{
              text: "托管人",
              value: "1",
            },
            {
              text: "房主本人",
              value: "0",
            },
          ]
        },
        options: {},
        formDictMap: [
          'fFwlb',
          'fFwxz',
          'fFwlx',
          'fFwzt',
          'fIszdgz',
          'fFwyt',
          'fSftgrtg',
          'fTgryfzgx',
          'fTgrMz',
        ],
        isEmpty: false,
        customSubmitStyleHalf,
        loading: false
      }
    },
    // 定义 actionType 'add' 'modify'  
    // 其他参数放在 params 里面
    onLoad(options) {
      if (options) {
        this.options = options
        // 编辑
        if (options.editOptions) {
          let editOptions = JSON.parse(options.editOptions);
          this.form = _.pick(editOptions, [...Object.keys(this.initForm()), 'fHouseid']);
          this.formDictMap.forEach(key => {
            this.$set(this.form, `${key}_text`, editOptions[`${key}Name`])
          })
          delete this.form.policeJurisdictionId;
          delete this.form.policeAgencyId;
        }
      }
    },
    onShow() {
      uni.$on('select-standard-address', (data) => {
        this.setStandardAddressInfo(data)
      })
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      moment,
      setStandardAddressInfo(data) {
        const {
          fJlxxqmc,
          fDzbm,
          roomName,
          jzFDzbm,
          dyFDzbm,
          lcFDzbm,
          fzFDzbm,
          jlxFDzbm,
          buildType
        } = data
        if (fJlxxqmc) this.$set(this.form, "fNames", fJlxxqmc);
        if (roomName) this.$set(this.form, "addressDetail", roomName);
        if (jzFDzbm) this.$set(this.form, "fSsjzwDzbm", jzFDzbm);
        if (dyFDzbm) this.$set(this.form, "fSsdyDzbm", dyFDzbm);
        if (lcFDzbm) this.$set(this.form, "fSslcDzbm", lcFDzbm);
        if (fzFDzbm) this.$set(this.form, "fSsjzwdyfwDzbm", fzFDzbm);
        if (jlxFDzbm) this.$set(this.form, 'fSsjlxxqDzbm', jlxFDzbm)
        if (buildType !== undefined) this.$set(this.form, 'buildType', buildType + '')
      },
      initForm() {
        return {
          addressDetail: '',
          fFwlx: '',
          fFwyt: ''
        }
      },
      onTimeChange(e) {
        this.form.openingTime = e
      },
      handleSubmit() {
        this.$refs.form.validate().then(async (res) => {
          // 成功返回，res 为表单数据
          let data = {
            ...this.form
          };
          // 编辑
          if (this.form.fHouseid) {
            this.loading = true
            try {
              let res = await postAction(`/mini/indeed/house/policeEidtHouseMain`, {
                ...this.form,
                houseid: this.form.fHouseid
              });
              if (res.code == 200) {
                Toast("提交成功！");
                setTimeout(() => {
                  navBack();
                }, 1000)
              } else {
                this.loading = false
              }
            } catch (e) {
              this.loading = false
            } finally {}

          }
        }).catch((err) => {
          // 表单校验验失败，err 为具体错误信息
        })
      },
      handleCancel() {
        navBack()
      },
      onGenerateFilePath(fileurl) {
        this.uploadImage(fileurl, 44);
      },
      handleCamera() {
        this.visibleCamera = true;
      },
      uploadImage(fileurl, type) {
        uploadFile({
            url: "/web/sys/upload/upload_file",
            filePath: fileurl,
            name: "file",
            formData: {
              type,
            },
            success: (res) => {},
          })
          .then((res) => {
            isLoading(false);
            let {
              fullPath,
              halfPath
            } = res.result;
            if (type == 44) {
              this.fileList = [];
              this.fileList.push({
                url: fullPath,
              });
              this.form.idCardImage = halfPath;
            }
          })
          .finally(() => {

          })
      },
      onParsedSuccess(value) {
        const {
          domicileAddress,
          userName,
          idcard,
          nation
        } = value;
        this.$set(this.form, "fTgrXm", userName);
        this.$set(this.form, "fTgrGmsfhm", idcard);
        let nationOption = selectNation(this.dictMapping, nation)
        if (nationOption) {
          this.form.fTgrMz = nationOption.value
          this.form.fTgrMz_text = nationOption.text
        }
        this.visibleCamera = false;
      },
      handleAddressClick() {
        uni.navigateTo({
          url: "/actual_real_estate/selectStandardAddress"
        });
      },
      handleArea(value, key) {
        value = value.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
        value = value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
        value = value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
        this.$nextTick(() => {
          this.$set(this.form, key, value)
        })
        if (value.indexOf(".") < 0 && value != "") { //以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
          value = parseFloat(value);
          this.$nextTick(() => {
            this.$set(this.form, key, value)
          })
        }
        if (value || value == '0' || value == '0.0' || value == '0.00') {
          return;
        }
        //  正常得话继续调后端接口
      },
      onPickerConfirm(data, formName = 'form') {
        let {
          value,
          text
        } = data.value[0];
        this[formName][this.pickerWithFormKey] = value;
        this.$set(this[formName], `${this.pickerWithFormKey}_text`, text);
        // 如果房屋类型发生了变化，则清空是否出租
        this.pickerShow = false;
      },
    }
  }
</script>

<style>
  page {
    background: #F9F9F9;
    box-sizing: border-box;
  }
</style>

<style lang="scss" scoped>
  @import "../../styles/uni-form.scss";
  @import "../../styles/submit-button.scss";

  .root {
    .content {
      .content-inner-wrapper {
        padding: 0 16rpx;
        border-radius: 16rpx 16rpx 16rpx 16rpx;
        background: #fff;
        margin-bottom: 10rpx;
      }

      .content-inner-wrapper-house {
        /deep/.uni-forms-item {
          border: 0;
        }
      }

      .content-inner-wrapper-house-manager {
        /deep/.uni-forms-item {
          border: 0;
        }
      }
    }

    /deep/.uni-forms {
      margin-bottom: 130rpx;
    }

    .title-require-style {
      font-weight: 500;
      font-size: 26rpx;
      color: #999999;
      height: 100rpx;
      display: flex;
      align-items: center;
    }
  }
</style>